import React, { PureComponent } from 'react';
import { Form, Upload, Button, message, Modal, Select, DatePicker } from 'antd';
import moment from 'moment';
import { CONST_DATE_FORMAT } from '@/constants';
import styles from './HandleFile.less';

// const CONST_FILE_TYPE = [
//     'application/vnd.ms-excel',
//     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
// ];
const CONST_FILE_TYPE = [
    'xls',
    'xlsx'
];

const { Option } = Select;

export default class Index extends PureComponent {
    constructor(props) {
        super(props);
        const { active } = props;
        this.state = {
            active,
            visible: false
        }
        this.refresh = false;
    }

    componentWillUnmount() {
        if (this.refresh) {
            const { dispatch, modularName } = this.props;

            dispatch({
                type: `${modularName}/changeState`,
                payload: {
                    refreshTime: new Date().valueOf()
                }
            });
        }
    }

    downloadTemplate = () => {
        const { currentUnit } = this.props;

        if (currentUnit && currentUnit.id && currentUnit.id !== -1) {
            const { dispatch, modularName, currentUnit, selectedTime } = this.props;

            dispatch({
                type: `${modularName}/downloadTemplate`,
                payload: {
                    unitId: currentUnit.id,
                    name: `${selectedTime.format('YYYY年MM月')}值班表(${currentUnit.unit_name}).xlsx`
                }
            });
        } else {
            message.error('请选择要导出模板的单位', 2);
        }
    }

    deriveExcel = () => {
        this.setState({ visible: true, type: 'deriveExcel' });
    }

    deriveWord = (type, parameters) => {
        this.setState({ visible: true, type, parameters });
    }

    disabledStartDate = (field, start) => {
        const { form } = this.props;
        const end = form.getFieldValue(field);

        if (!start || !end) {
            return false;
        }
        return start.valueOf() > end.valueOf();
    }

    disabledEndDate = (field, end) => {
        const { form } = this.props;
        const start = form.getFieldValue(field);

        if (!start || !end) {
            return false;
        }
        return end.valueOf() <= start.valueOf();
    }

    exportBtnClick = () => {
        const { type, parameters } = this.state;
        const { dispatch, form, modularName, units = [], currentUnit, selectedTime } = this.props;

        form.validateFields((err, values) => {
            if (!err) {
                const { unit_id, start_date, end_date, shift_date, shift_date_end } = values;
                const filter = units.filter(item => item.id === unit_id);
                const unitName = filter && filter[0] ? filter[0].unit_name : currentUnit.unit_name;
                let payload = {};

                if (type === 'deriveExcel') {
                    payload = {
                        startDate: start_date.format(CONST_DATE_FORMAT),
                        endDate: end_date.format(CONST_DATE_FORMAT),
                        shift_unit: { id: unit_id },
                        name: `${selectedTime.format('YYYY年MM月')}值班表(${unitName}).xlsx`,
                        callback: () => {
                            this.setState({ visible: false });
                        }
                    }
                } else if (type === 'deriveWord') {
                    payload = {
                        startDate: start_date ? start_date.format(CONST_DATE_FORMAT) : undefined,
                        endDate: end_date ? end_date.format(CONST_DATE_FORMAT) : undefined,
                        unitIdList: unit_id === -1 ? [] : [unit_id],
                        name: `${selectedTime.format('YYYY年MM月')}值班表${unit_id === -1 ? '' : `(${unitName})`}.docx`,
                        callback: () => {
                            this.setState({ visible: false });
                        }
                    }
                } else {
                    if (parameters.type === '值班') {
                        payload = {
                            ...parameters,
                            startDate: start_date ? start_date.format(CONST_DATE_FORMAT) : undefined,
                            endDate: end_date ? end_date.format(CONST_DATE_FORMAT) : undefined,
                            shift_unit: { id: unit_id === -1 ? undefined : unit_id },
                            name: `${selectedTime.format('YYYY年MM月')}值班表${unit_id === -1 ? '' : `(${unitName})`}.docx`,
                            callback: () => {
                                this.setState({ visible: false });
                            }
                        }
                    } else {
                        const diff = shift_date_end.diff(shift_date, 'days');
                        const option = [];
                        for (let i = 0; i <= diff; i++) {
                            option.push({
                                shift_date: moment(shift_date).add(i, 'd').format(CONST_DATE_FORMAT),
                                shift_unit: { id: unit_id === -1 ? undefined : unit_id }
                            });
                        }

                        payload = {
                            ...parameters,
                            name: `${diff === 0 ? shift_date.format('YYYY年MM月DD日') : `${shift_date.format('YYYY年MM月DD日')}到${shift_date_end.format('YYYY年MM月DD日')}`}值班表${unit_id === -1 ? '' : `(${unitName})`}.docx`,
                            option,
                            callback: () => {
                                this.setState({ visible: false });
                            }
                        }
                    }
                }

                dispatch({ type: `${modularName}/${type}`, payload });
            }
        });
    }

    render() {
        const { active, visible, state, errorNum, error, type, parameters = {} } = this.state;
        const { dispatch, form, loading, modularName, isAdmin, currentUnit = {}, units = [], selectedTime } = this.props;
        const { getFieldDecorator } = form;

        const props = {
            accept: CONST_FILE_TYPE.join(','),
            fileList: [],
            beforeUpload: (file, fileList) => {
                const { currentUnit = {} } = this.props;

                if (!currentUnit.id || currentUnit.id === -1) {
                    message.error('请选择要导入人员数据的单位', 2);
                } else {
                    if (file) {
                        const { name, type } = file;
                        const fileType = name.substring(name.lastIndexOf('.') + 1);

                        if (CONST_FILE_TYPE.includes(fileType)) {
                            dispatch({
                                type: `${modularName}/uploadData`,
                                payload: {
                                    unitId: currentUnit.id,
                                    file,
                                    callback: (state, errorNum, error) => {
                                        this.refresh = true;
                                        this.setState({ state, errorNum, error });
                                    }
                                }
                            });
                        } else {
                            message.error('不支持的文件类型', 2);
                        }
                    }
                }

                return false;
            }
        };

        return (
            <div>
                <div className={styles.content}>
                    {active === '1' ?
                        <>
                            <div className={styles.option}>
                                <div>
                                    <span>1.下载排班模板</span>
                                    <div className={styles.img_wrapper}>
                                        <img src='/img/fileType/download.png' />
                                        <div className={styles.desc}>

                                        </div>
                                        <div>
                                            <Button shape='round' size='large' loading={!!loading.effects[`${modularName}/downloadTemplate`]} onClick={this.downloadTemplate}>下载模板</Button>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <span>2.上传填好的文件</span>
                                    <div className={styles.img_wrapper}>
                                        <img src='/img/fileType/upload.png' />
                                        <div className={styles.desc}>
                                            仅支持XLS、XLSX格式文件
                                        </div>
                                        <div>
                                            <Upload {...props}>
                                                <Button shape='round' size='large' type='primary' style={{ minWidth: 138 }} >选择文件</Button>
                                            </Upload>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className={styles.message}>
                                {state === '200' && errorNum === 0 &&
                                    <div className={styles.success}>
                                        导入成功
                                    </div>
                                }
                                {state === '200' && errorNum > 0 &&
                                    <div className={styles.error}>
                                        <div>
                                            导入完成, 部分数据异常导入失败, 共{errorNum}条
                                        </div>
                                        <ul>
                                            {Array.isArray(error) && error.map(item => {
                                                return <li>{item}</li>
                                            })}
                                        </ul>
                                    </div>
                                }
                                {state === '400' &&
                                    <div className={styles.error}>
                                        文件模板失效
                                    </div>
                                }
                                {state === '500' &&
                                    <div className={styles.error}>
                                        导入失败
                                    </div>
                                }
                            </div>
                            <div className={styles.tips}>
                                <ul>
                                    <li>上传文件之前请先下载模板，根据模板填写好排班数据。</li>
                                    <li>文件上传之后会直接覆盖现有已排班数据。</li>
                                    <li>值班日期可自行复制行添加。</li>
                                    <li>如果需要修改值班头衔，请在系统“头衔管理”中修改之后重新导出模板。</li>
                                    <li>如果需要修改值班班次，请在系统“班次管理”中修改之后重新导出模板。</li>
                                </ul>
                            </div>
                        </> :
                        <div style={{ minHeight: 540 }}>
                            <div className={styles.export_item}>
                                <div>
                                    <div className={styles.img}>
                                        <img src='/img/template/01.png' />
                                    </div>
                                    <div className={styles.button}>
                                        <Button icon='download' size='small' type='primary' onClick={this.deriveExcel} loading={!!loading.effects[`${modularName}/deriveExcel`]}>导出</Button>
                                    </div>
                                </div>
                            </div>
                            <div className={styles.export_item}>
                                <div>
                                    <div className={styles.img}>
                                        <img src='/img/template/03.png' />
                                    </div>
                                    <div className={styles.button}>
                                        <Button icon='download' size='small' type='primary' onClick={this.deriveWord.bind(this, 'downloadWord', { type: '值班' })} loading={!!loading.effects[`${modularName}/downloadWord`]}>导出</Button>
                                    </div>
                                </div>
                            </div>
                            {isAdmin &&
                                <div className={styles.export_item}>
                                    <div>
                                        <div className={styles.img}>
                                            <img src='/img/template/04.png' />
                                        </div>
                                        <div className={styles.button}>
                                            <Button icon='download' size='small' type='primary' onClick={this.deriveWord.bind(this, 'deriveWord', {})} loading={!!loading.effects[`${modularName}/deriveWord`]}>导出</Button>
                                        </div>
                                    </div>
                                </div>
                            }
                            <div className={styles.export_item}>
                                <div>
                                    <div className={styles.img}>
                                        <img src='/img/template/05.png' />
                                    </div>
                                    <div className={styles.button}>
                                        <Button icon='download' size='small' type='primary' onClick={this.deriveWord.bind(this, 'downloadWord', { type: '值班汇总' })} loading={!!loading.effects[`${modularName}/downloadWord`]}>导出</Button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    }
                </div>
                <Modal
                    centered
                    destroyOnClose
                    maskClosable={false}
                    title='导出选项'
                    visible={!!visible}
                    wrapClassName={styles.common_modal_wrapper}
                    footer={null}
                    onCancel={() => {
                        this.setState({ visible: false })
                    }}
                >
                    <Form layout='vertical'>
                        <Form.Item label='导出单位'>
                            {getFieldDecorator('unit_id', {
                                initialValue: isAdmin && (type === 'deriveWord' || (type === 'downloadWord' && parameters && parameters.type === '值班汇总')) ? -1 : currentUnit.id !== -1 ? currentUnit.id : undefined,
                                rules: [{ required: true, message: '该项为必填项' }]
                            })(
                                <Select placeholder='请选择导出单位' size='large'>
                                    {isAdmin && (type === 'deriveWord' || (type === 'downloadWord' && parameters && parameters.type === '值班汇总')) &&
                                        <Option value={-1}>全部单位</Option>
                                    }
                                    {units && units.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.unit_name}</Option>
                                    })}
                                </Select>
                            )}
                        </Form.Item>
                        {parameters && parameters.type === '值班汇总' ?
                            <>
                                <Form.Item label='导出时间' style={{ display: 'inline-block', verticalAlign: 'top' }}>
                                    {getFieldDecorator('shift_date', {
                                        initialValue: moment().startOf('day')
                                    })(
                                        <DatePicker
                                            allowClear={false}
                                            // disabledDate={this.disabledStartDate.bind(this, 'shift_date_end')}
                                            placeholder='开始时间'
                                            size='large'
                                            style={{ width: 225 }}
                                        />
                                    )}
                                    <span style={{ margin: '0 5px' }}>~</span>
                                </Form.Item>
                                <Form.Item label={<div style={{ height: 21 }} />} style={{ display: 'inline-block', verticalAlign: 'top' }}>
                                    {getFieldDecorator('shift_date_end', {
                                        initialValue: moment().endOf('day')
                                    })(
                                        <DatePicker
                                            allowClear={false}
                                            // disabledDate={this.disabledEndDate.bind(this, 'shift_date')}
                                            placeholder='结束时间'
                                            size='large'
                                            style={{ width: 225 }}
                                        />
                                    )}
                                </Form.Item>
                            </> :
                            <>
                                <Form.Item label='导出时间' style={{ display: 'inline-block', verticalAlign: 'top' }}>
                                    {getFieldDecorator('start_date', {
                                        initialValue: moment(selectedTime).startOf('month')
                                    })(
                                        <DatePicker
                                            allowClear={false}
                                            // disabledDate={this.disabledStartDate.bind(this, 'end_date')}
                                            placeholder='开始时间'
                                            size='large'
                                            style={{ width: 225 }}
                                        />
                                    )}
                                    <span style={{ margin: '0 5px' }}>~</span>
                                </Form.Item>
                                <Form.Item label={<div style={{ height: 21 }} />} style={{ display: 'inline-block', verticalAlign: 'top' }}>
                                    {getFieldDecorator('end_date', {
                                        initialValue: moment(selectedTime).endOf('month')
                                    })(
                                        <DatePicker
                                            allowClear={false}
                                            // disabledDate={this.disabledEndDate.bind(this, 'start_date')}
                                            placeholder='结束时间'
                                            size='large'
                                            style={{ width: 225 }}
                                        />
                                    )}
                                </Form.Item>
                            </>
                        }
                        <Button icon='download' shape='round' size='large' style={{ margin: '0 120px', width: 240 }} type='primary' onClick={this.exportBtnClick}>导出</Button>
                    </Form>
                </Modal>
            </div>
        );
    }
}